package NG::Sys::Cached::DBColumn;
use strict;
use warnings;
use utf8;

use JSON::XS;

use base 'NG::Sys::Cached::Base';

sub init {
	my ($self) = @_;
	$self->SUPER::init;
	unless($self->{table}){
		die "need table\n";
	}
	unless($self->{pkey}){
		die "need pkey\n";
	}
	unless($self->{nkey}){
		die "need nkey\n";
	}
	unless($self->{vkey}){
		die "need vkey\n";
	}
	if($self->{hash_fields}{$self->{pkey}}){
		die $self->{pkey}." present in fields\n";
	}
	unless($self->{dbh}){
		die "need dbh";
	}
	$self->{sth}{read} = $self->{dbh}->prepare("select `".$self->{nkey}."`,`".$self->{vkey}."` from `".$self->{table}."` where `".$self->{pkey}."`=?");
	$self->{sth}{update} = $self->{dbh}->prepare("replace `".$self->{table}."` (`".$self->{pkey}."`,`".$self->{nkey}."`,`".$self->{vkey}."`) values (?,?,?)");
	$self->{sth}{remove} = $self->{dbh}->prepare("delete from `".$self->{table}."` where `".$self->{pkey}."`=?");
}
sub _remove_source {
	my ($self,$id) = @_;
	my $sth = $self->{sth}{remove};
	$sth->execute($id);
}
sub _read_source {
	my ($self,$id) = @_;
	my $sth = $self->{sth}{read};
	$sth->execute($id);
	my $ary = $sth->fetchall_arrayref;
	my %data;
	my $blob = $self->{blob};
	for my $row(@$ary){
		#$data{$row->[0]} = $row->[1];
		my $v = $row->[1];
		$data{$row->[0]} =  $blob && defined $v ? decode_json($v) : $v;
	}
	return \%data;
}
sub _replace_source {
	goto &_update_source;
}
sub _update_source {
	my ($self,$id,$data,$keys) = @_;
	unless($keys or @$keys){
		return 0;
	}
	my $sth = $self->{sth}{update};
	my $blob = $self->{blob};
	for my $key(@$keys){
		my $v = $data->{$key};
		$sth->execute($id,$key,$blob && defined $v && ref $v ? encode_json($v) : $v);
	}
	return $keys;
}


1;
